package org.linlinjava.litemall.admin.web;

import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.LitemallUserGoldcoinRecord;
import org.linlinjava.litemall.db.service.LitemallUserGoldcoinRecordService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/admin/user")
@Validated
public class AdminUserController {
    private final Log logger = LogFactory.getLog(AdminUserController.class);

    @Autowired
    private LitemallUserService userService;

    @Autowired
    private LitemallUserGoldcoinRecordService litemallUserGoldcoinRecordService;

    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String username, String mobile,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<LitemallUser> userList = userService.querySelective(username, mobile, page, limit, sort, order);
        return ResponseUtil.okList(userList);
    }
    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "详情")
    @GetMapping("/detail")
    public Object userDetail(@NotNull Integer id) {
    	LitemallUser user=userService.findById(id);
        return ResponseUtil.ok(user);
    }
    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "编辑")
    @PostMapping("/update")
    public Object userUpdate(@RequestBody LitemallUser user) {
        return ResponseUtil.ok(userService.updateById(user));
    }

    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "积分管理"}, button = "")
    @PostMapping("/userGoldCoinUpdate")
    public Object userGoldCoinUpdate(@RequestBody LitemallUser user) {
        LitemallUserGoldcoinRecord goldcoinRecord=new LitemallUserGoldcoinRecord();
        goldcoinRecord.setGoldcoin(user.getGoldcoin());
        goldcoinRecord.setDirection(1);
        goldcoinRecord.setUserId(Long.valueOf(user.getId()));
        goldcoinRecord.setName("积分充值");
        goldcoinRecord.setInfo("管理员操作");
        return ResponseUtil.ok(litemallUserGoldcoinRecordService.addGoldCoin(goldcoinRecord));
    }



    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "积分管理"}, button = "积分记录")
    @GetMapping("/userGoldCoinDetail")
    public Object userGoldCoinDetail(@NotNull Long id) {
        return ResponseUtil.ok(litemallUserGoldcoinRecordService.queryByIdUserId(id));
    }

    /**
     * 通用上传请求（单个）
     */
    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "积分上传"}, button = "")
    @PostMapping("/userGoldCoinUpload")
    public Object uploadFile(MultipartFile file, HttpServletRequest request) throws Exception
    {
        try
        {
            List<LitemallUserGoldcoinRecord> result = new ArrayList<>();
            File f = FileUtil.createTempFile();
            FileUtils.copyInputStreamToFile(file.getInputStream(), f);
            // 上传文件路径
            ExcelReader reader = ExcelUtil.getReader(f,0);
            List<List<Object>> dataAll = reader.read();
            for (int i=1;i<dataAll.size();i++){
                List<Object> data = dataAll.get(i);
                String phone = data.get(0).toString();
                List<LitemallUser> userList = userService.queryByMobile(phone);
                if(!CollectionUtils.isEmpty(userList)){
                    LitemallUserGoldcoinRecord goldcoinRecord=new LitemallUserGoldcoinRecord();
                    goldcoinRecord.setGoldcoin(Integer.valueOf(data.get(1).toString()));
                    goldcoinRecord.setDirection(1);
                    goldcoinRecord.setUserId(Long.valueOf(userList.get(0).getId()));
                    goldcoinRecord.setName("积分充值");
                    goldcoinRecord.setInfo("管理员操作");
                    result.add(goldcoinRecord);
                }
            }
            if(!CollectionUtils.isEmpty(result)){
                for (LitemallUserGoldcoinRecord goldcoinRecord:result){
                    litemallUserGoldcoinRecordService.addGoldCoin(goldcoinRecord);
                }
                return ResponseUtil.ok("上传成功");
            }else {
                return ResponseUtil.ok("未找到有效用户");
            }
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            return ResponseUtil.fail(500,e.getMessage());
        }
    }


}
